package org.monster.context.core.communicator;

import org.monster.context.core.parameter.HttpResponse;
import org.monster.context.core.processor.ProcessRequest;
import org.monster.context.core.request.HttpRequest;

import java.io.*;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Http通信器
 *
 * @author Monster
 */
public class HttpCommunicator implements Communicator {

    /**
     * 日志器
     */
    private static final Logger logger = Logger.getLogger(HttpCommunicator.class.getName());
    /**
     * 套接字
     */
    private Socket socket;

    /**
     * @param socket 套接字
     */
    public HttpCommunicator(Socket socket) {
        this.socket = socket;
    }

    /**
     * 接收
     * 接收Socket对象包含的请求的信息，并最终关闭Socket
     */
    @Override
    public void receive() {
        try {
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            DataInputStream input = new DataInputStream(inputStream);
            PrintStream output = new PrintStream(outputStream);
            send(input, output);
            socket.close();
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }

    /**
     * 发送
     * 执行通信 创建request,response，由KernelController控制协调请求和响应
     *
     * @param is 输入流
     * @param os 输出流
     */
    public void send(InputStream is, OutputStream os) {
        HttpRequest httpRequest = new HttpRequest(is);
        HttpResponse httpResponse = new HttpResponse(os);
        assemblyData(httpRequest);
        ProcessRequest processRequest = new ProcessRequest(new HttpHeader(), httpRequest,
                httpResponse);
        String headerInfo = processRequest.getRequestInfo();
        if (headerInfo != null && !"".equals(headerInfo)) {
            httpRequest.setHeaderInfo(headerInfo);
            processRequest.processBase(headerInfo);
        }
    }

    /**
     * 填充数据
     * 填充必要Socket信息到Request
     *
     * @param request 请求
     */
    private void assemblyData(HttpRequest request) {
        request.setServerPort(socket.getPort());
    }
}
